using System;
using System.Collections;
using System.Data;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Agreements;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.InsightWebControls;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;
using PHSRAG.SharePointUtility;
using PHSRAG.Security;
using System.Xml;
using System.IO;
using System.Text;
using System.Net.Mail;
using PHSRAG.Insight21.CDS;
using PHSRAG.WebControls;
using System.Security.Principal;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
using Helper = PHSRAG.WebControls.Helper;

namespace PHSRAG.Insight21.Agreements
{
    public partial class AdvanceFundRequestForm : NoCachePage
    {
        #region Constants

        private const string PageCacheKey = "pageCacheKey_19309A7A-1206-497d-8D9F-189E5152CE59";
        private const string CurrentPageIndexKey = "AdvanceFundRequestFormIndexKey_119B5DD3-0ED1-45f0-B455-6F9C0473E580";
        private const string PropNum = "AdvanceFundRequestLandingPropNum_B6836CCD-FA0B-4690-A0FC-52352E590F6C";
        private const string PageName = "Advance Fund Request Form";

        #endregion

        #region Enums (Private)
        
        private enum AttachmentsTableColumnIndex
        {
            ID,
            PropNumber,
            UploadedDate,
            UploadedBy,
            DocumentName,
            View,
            Delete           
        }

        private enum WorkflowStatus
        {            
            Draft = 1,
            AwaitingPISignoff,
            AwaitingDepartmentSignoff,
            AwaitingGASignoff,
            Completed,
            Denied
        }
        
        #endregion

        #region Private Variables

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        private int loggedInUserID;
        private static int loggedID;
        private DataTable dtGrid;
        private string EmailTemplate = "";
        private string PageUrl = "";

        #endregion

        #region Private Properties

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AdvanceFundRequestFormPageKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int)h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AdvanceFundRequestFormPageKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;

                pageCachePolicy.Cache(Keys.AdvanceFundRequestFormPageKey, h);
            }
        }

        private string ProposalNumber
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AdvanceFundRequestLandingPageKey) as Hashtable;
                return (h == null || h[PropNum] == null) ? "" : h[PropNum].ToString();
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.AdvanceFundRequestLandingPageKey) as Hashtable ?? new Hashtable();
                h[PropNum] = value;

                pageCachePolicy.Cache(Keys.AdvanceFundRequestLandingPageKey, h);
            }
        }

        #endregion
        
        #region Event Handlers

        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
            AddRows(5);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int Status = 0;
                annunciator.Message = string.Empty;
                breadCrumb.Add("Advance Fund Request", Settings.GetKeyValue("SubNavigation.Agreements.AdvanceFundRequestLandingURL", ""), 1);
                breadCrumb.Add("Advance Request Form", Settings.GetKeyValue("SubNavigation.Agreements.AdvanceFundRequestFormURL", ""), 2);

                UserContext user = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
                loggedInUserID = user.DomainUserId;
                loggedID = loggedInUserID;                

                // setting the insight url for the email link based on the current environment.                
                PageUrl = Utility.Settings.GetKeyValue("Email.AdvanceFundRequest.LinkUrl", "https://insight.partners.org/Agreements/AdvanceFundRequestForm.aspx");                             

                if (!IsPostBack)
                {   
                    lblRequestedBy.Text = user.LastName + " " + user.FirstName + " on " + DateTime.Now.ToShortDateString();                    

                    string QueryString = ProposalNumber; 
                    if (QueryString == "0")
                    {
                        ClearPageData();
                    }
                    else
                    {
                        txtPropNumber.Text = QueryString;
                        imgBtnInfo.Enabled = false;
                        txtPropNumber.Enabled = false;

                        DataTable dt = GetInfoByProposalNumber(QueryString);
                        if (dt.Rows.Count > 0)
                        {
                            LoadPageData(dt);
                        }

                        if (Convert.ToInt32(dt.Rows[0]["CreatedBy"].ToString()) != loggedInUserID)
                        {
                            gvDocs.Columns[(int)AttachmentsTableColumnIndex.Delete].Visible = false;
                        }

                        //check the workflow status for this fund request.
                        Status = Convert.ToInt32(dt.Rows[0]["Status"].ToString());

                        if (Status < (int)WorkflowStatus.AwaitingPISignoff)
                        {
                            if (Convert.ToInt32(dt.Rows[0]["CreatedBy"].ToString()) != loggedInUserID)
                            {
                                imgBtnSaveDraft.Visible = false;
                                imgBtnSubmit.Visible = false;
                                txtComments.Enabled = false;
                            }
                        }
                        else
                        {
                            if (Status == (int)WorkflowStatus.AwaitingPISignoff)
                            {
                                if (Convert.ToInt32(dt.Rows[0]["PIId"].ToString() == "" ? "0" : dt.Rows[0]["PIId"].ToString()) != loggedInUserID)
                                {
                                    fu1.Enabled = false;
                                }
                                else
                                {
                                    lblStatus.Text = "2";
                                    fu1.Enabled = false;
                                }
                            }
                            else if (Status == (int)WorkflowStatus.AwaitingDepartmentSignoff)
                            {
                                if (Convert.ToInt32(dt.Rows[0]["ChiefId"].ToString() == "" ? "0" : dt.Rows[0]["ChiefId"].ToString()) != loggedInUserID && Convert.ToInt32(dt.Rows[0]["DelegateId"].ToString() == "" ? "0" : dt.Rows[0]["DelegateId"].ToString()) != loggedInUserID)
                                {
                                    fu1.Enabled = false;
                                }
                                else
                                {
                                    lblStatus.Text = "3";
                                    fu1.Enabled = false;
                                }
                            }
                            else if (Status == (int)WorkflowStatus.AwaitingGASignoff)
                            {
                                if (Convert.ToInt32(dt.Rows[0]["GAId"].ToString() == "" ? "0" : dt.Rows[0]["GAId"].ToString()) != loggedInUserID)
                                {
                                    fu1.Enabled = false;
                                }
                                else
                                {
                                    lblStatus.Text = "4";
                                    fu1.Enabled = false;
                                }
                            }
                            else if (Status == (int)WorkflowStatus.Completed || Status == (int)WorkflowStatus.Denied)
                            {
                                fu1.Enabled = false;
                            }
                            txtComments.Enabled = false;
                            imgBtnSaveDraft.Visible = false;
                            imgBtnSubmit.Visible = false;
                        }

                        dt = GetCommentsByProposalNumber(QueryString);
                        txtComments.Text = dt.Rows[0]["Comment"].ToString();
                        bool AuthReq = false;
                        if (Utility.Settings.GetKeyValue("ADAuthentication", "false").ToString() == "true")
                        {
                            AuthReq = true;
                        }                       
                        
                        dt = GetUploadedDocument(QueryString);
                        if (dt.Rows.Count > 0)
                        {
                            gvDocs.DataSource = dt;
                            gvDocs.DataBind();

                            foreach (GridViewRow row in gvDocs.Rows)
                            {

                                ImageButton lnkAction = (ImageButton) row.Cells[3].FindControl("ibView");
                                lnkAction.OnClientClick = "javascript:window.open('../Research/downloadform.aspx?FileUrl=" + lnkAction.ToolTip.ToString() + "', 'OpenFile', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                            }
                        }

                        if (fu1.Enabled == false)
                        {
                            for (int i = 2; i <= 5; i++)
                            {
                                FileUpload fup = new FileUpload();
                                fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                                fup.Visible = false;
                            }
                        }
                        else
                        {
                            for (int i = 5; i > 5 - dt.Rows.Count; i--)
                            {
                                FileUpload fup = new FileUpload();
                                fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                                fup.Visible = false;
                            }
                            if (fu1.Visible == false)
                            {
                                fu1.Visible = true;
                                fu1.Enabled = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// GetInfoByProposalNumber returns a resultset.
        /// </summary>
        /// <returns>DataTable</returns>
        private DataTable GetInfoByProposalNumber(string PropNumber)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                dtGrid = ar.GetInfoByProposalNumber(DataAccess.GetConnectionString(), PropNumber);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
            return dtGrid;
        }

        private DataTable GetCommentsByProposalNumber(string PropNumber)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                dtGrid = ar.GetCommentsByProposalNumber(DataAccess.GetConnectionString(), PropNumber);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
            return dtGrid;
        }

        private DataTable GetUploadedDocument(string PropNumber)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                dtGrid = ar.GetUploadedDocument(DataAccess.GetConnectionString(), PropNumber);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
            return dtGrid;
        }

        private void UploadDocumentsToSharePoint(string PropNumber, int UploadedBy, int StatusType)
        {
            WindowsImpersonationContext wic = null;
            try
            {
                int DocId = 0;
                int OpState = 0;
                string DocumentYear = "";
                string DestinationUrl = "";
                string InfoEdUrl = "";
                string BaseUrl = "";
                string FileUrl = "";
                string newFilePath = "";
                string newFileName = "";
                bool isClean = true;
                string stagingFolder = Settings.GetKeyValue("StagingFolder", string.Empty);

                wic = Authenticator.ImpersonateUser(
                                Settings.GetKeyValue("ServiceAccount", "RAG29"),
                                Settings.GetKeyValue("SAPassword", "z0hcq"),
                                Authenticator.LogonType.NewCredentials, Authenticator.LogonProvider.WinNT50);

                for (int i = 1; i <= 5; i++)
                {
                    FileUpload fup = new FileUpload();
                    fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                    if (fup != null)
                    {
                        if (fup.FileName.Trim() != "")
                        {
                            isClean = true;
                            // scanning the document
                            if (bool.Parse(Settings.GetKeyValue("VirusScanner.Enable", "false")))
                            {
                                try
                                {
                                    Document.ScanFileForVirus(fup.PostedFile.FileName.Trim());
                                }
                                catch (Exception ex)
                                {
                                    isClean = false;                                    
                                }
                            }
                            if (isClean)
                            {
                                DocumentYear = lblPropNo.Text.Trim().Substring(0, 4);
                                DestinationUrl = "AdvanceFundRequest";
                                InfoEdUrl = Utility.Settings.GetKeyValue("SharePointBlobURLInfoEd", "http://stage-infoeddocuments.partners.org/proposals/");
                                BaseUrl = InfoEdUrl + DocumentYear + "/Documents";
                                string[] Ext = fup.FileName.Split('.');

                                // store the data in the table and retrieve the RowId
                                DocId = SaveDocumentMetaData(PropNumber, UploadedBy, fup.FileName);
                                FileUrl = BaseUrl + "/" + DestinationUrl + "/" + DocId.ToString() + "." + Ext[1];
                                if (DocId > 0)
                                {
                                    // Create the folder hierchy in Sharepoint if not present.
                                    DocumentLibrary dl = new DocumentLibrary();
                                    dl.CreateDocumentFolderStructure(DestinationUrl, BaseUrl);
                                    try
                                    {
                                        newFileName = fup.FileName;
                                        newFilePath = Path.Combine(stagingFolder, newFileName);

                                        // Save the file to the server first
                                        if (File.Exists(newFilePath))
                                        {
                                            File.Delete(newFilePath);
                                        }
                                        fup.SaveAs(newFilePath);

                                        // Upload the document to SharePoint                                
                                        dl.SaveFileToSharePoint(FileUrl, newFilePath);
                                        OpState = 1;
                                        /*at098 - Generate the url dynamically on demand*/
                                        UpdateDocumentMetaData(DocId, FileUrl, OpState);
                                    }
                                    catch (Exception ex)
                                    {
                                        OpState = 0;
                                        throw ex;
                                    }
                                    finally
                                    {
                                        if (OpState == 0)
                                        {
                                            UpdateDocumentMetaData(DocId, FileUrl, OpState);
                                        }
                                        if (File.Exists(newFilePath))
                                        {
                                            File.Delete(newFilePath);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
            finally
            {
                Authenticator.RevertUser(wic);
            }
        }

        private int SaveDocumentMetaData(string PropNumber, int UploadedBy, string FileName)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                return ar.SaveDocumentMetaData(DataAccess.GetConnectionString(), PropNumber, UploadedBy, FileName);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void UpdateDocumentMetaData(int DocId, string FileUrl, int OpState)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                ar.UpdateDocumentMetaData(DataAccess.GetConnectionString(), DocId, FileUrl, OpState);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void SaveFundRequest(string PropNumber, int CreatedBy, string Comment, int StatusType)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                ar.SaveFundRequest(DataAccess.GetConnectionString(), PropNumber, CreatedBy, Comment, StatusType);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void SaveFundRequestEmailNotification(string PropNumber, int EmailedToId, int EmailedById, string Subject, string MessageBody, int StatusType)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                ar.SaveFundRequestEmailNotification(DataAccess.GetConnectionString(), PropNumber, EmailedToId, EmailedById, Subject, MessageBody, StatusType);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void ApproveFundRequest(string PropNumber, int CreatedBy, string FundNumber, int StatusType)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                ar.ApproveFundRequest(DataAccess.GetConnectionString(), PropNumber, CreatedBy, FundNumber, StatusType);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void DeclineFundRequest(string PropNumber, int CreatedBy, string Reason, int StatusType)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                ar.DeclineFundRequest(DataAccess.GetConnectionString(), PropNumber, CreatedBy, Reason, StatusType);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        private void DeleteFundRequestDocument(string FileUrl)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            try
            {
                string[] Doc = FileUrl.Split('/');
                string[] Id = Doc[Doc.Length - 1].Split('.');
                ar.DeleteFundRequestDocument(DataAccess.GetConnectionString(), Convert.ToInt32(Id[0].ToString()));

                // update the attachments list.
                DataTable dt = GetUploadedDocument(lblPropNo.Text.Trim());                
                gvDocs.DataSource = dt;
                gvDocs.DataBind();

                if (dt.Rows.Count > 0)
                {
                    foreach (GridViewRow row in gvDocs.Rows)
                    {
                        ImageButton lnkAction = (ImageButton)row.Cells[3].FindControl("ibView");
                        lnkAction.OnClientClick = "javascript:window.open('../Research/downloadform.aspx?FileUrl=" + lnkAction.ToolTip.ToString() + "', 'OpenFile', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    }
                }

                // update the number the upload controls.
                for (int i = 1; i <= 5; i++)
                {
                    FileUpload fup = new FileUpload();
                    fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                    fup.Visible = true;
                }

                for (int i = 5; i > 5 - dt.Rows.Count; i--)
                {
                    FileUpload fup = new FileUpload();
                    fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                    fup.Visible = false;
                }
                if (fu1.Visible == false)
                {
                    fu1.Visible = true;
                    fu1.Enabled = false;
                }

                annunciator.Message = "The document has been deleted successfully.";
                //DocumentLibrary dl = new DocumentLibrary();
                //dl.DeleteDocumentforAdvanceFund(FileUrl);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
        }

        [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
        public static string[] GetProposalNumberList(string prefixText, int count)
        {
            AdvanceFundRequest ar = new AdvanceFundRequest();
            string[] items = null;
            try
            {
                DataTable dtList = ar.GetProposalNumberList(DataAccess.GetConnectionString(), loggedID, prefixText, count);
                if (dtList.Rows.Count > 0)
                {
                    items = new string[dtList.Rows.Count];
                    int i = 0;
                    foreach (DataRow dr in dtList.Rows)
                    {
                        items.SetValue(dr[0].ToString(), i);
                        i++;
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e.InnerException);
            }
            return items;
        }

        public static void SendEmail(string FromEmail, string ToEmail, string EmailSubject, string EmailBody)
        {
            MailMessage mailMessage = new MailMessage(FromEmail, ToEmail);
            mailMessage.IsBodyHtml = true;

            mailMessage.Subject = EmailSubject;
            mailMessage.Body = EmailBody;

            SmtpClient client = new SmtpClient(Utility.Settings.GetKeyValue("SmtpServer", "SMTP.Partners.org"));
            client.Send(mailMessage);
        }

        private bool SendEmailNotification(string To, string Subject, string Message)
        {
            try
            {
                string From = Utility.Settings.GetKeyValue("Email.AdvanceFundRequest.Admin", "InsightHelpDesk@partners.org");
                SendEmail(From, To, Subject, Message);
            }
            catch(Exception ex)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = PHSRAG.Insight21.InsightUtilities.Constants.Annunciator.Title;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Method to populate the page data.
        /// </summary>
        /// <param name="dt"></param>
        private void LoadPageData(DataTable dt)
        {
            try
            {
                lblPI.Text = dt.Rows[0]["PIName"].ToString();
                lblProjectTitle.Text = dt.Rows[0]["Title"].ToString();
                lblOrganization.Text = dt.Rows[0]["Organization"].ToString();
                lblChiefOfServiceCode.Text = dt.Rows[0]["COS"].ToString();
                lblSponsor.Text = dt.Rows[0]["SponsorName"].ToString();
                lblDept.Text = dt.Rows[0]["Department"].ToString();
                lblPeriodEndDate.Text = dt.Rows[0]["PeriodDate"].ToString();
                lblResearchMgmtAdmin.Text = dt.Rows[0]["GAName"].ToString();
                lblDeptAdmin.Text = dt.Rows[0]["DAName"].ToString();
                lblPropNo.Text = dt.Rows[0]["PropNumber"].ToString();
                lblInstrument.Text = dt.Rows[0]["InstrumentType"].ToString();
                lblOriginSponsor.Text = dt.Rows[0]["OriginatingSponsor"].ToString();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        private void ClearPageData()
        {
            lblChiefOfServiceCode.Text = "";
            lblDept.Text = "";
            lblProjectTitle.Text = "";
            lblOrganization.Text = "";
            lblPI.Text = "";
            lblSponsor.Text = "";
            lblPeriodEndDate.Text = "";
            lblResearchMgmtAdmin.Text = "";
            lblDeptAdmin.Text = "";
            lblPropNo.Text = "";
            lblInstrument.Text = "";
            lblOriginSponsor.Text = "";
        }

        /// <summary>
        /// Method to add the uploadFile controls at runtime.
        /// </summary>
        /// <param name="count"></param>
        private void AddRows(int count)
        {
            try
            {
                for (int i = 2; i <= count; i++)
                {
                    TableRow tr = new TableRow();
                    TableCell tcfu = new TableCell();
                    FileUpload fup = new FileUpload();
                    fup.ID = "fu" + i.ToString();
                    tcfu.Controls.Add(fup);
                    TableCell tcbtn = new TableCell();
                    tr.Cells.Add(tcfu);
                    tblMin.Rows.Add(tr);
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }
       
        #endregion

        protected void imgBtnInfo_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                if (txtPropNumber.Text.Trim() == "")
                {
                    ClearPageData();
                    annunciator.Message = "Please provide a Proposal Number.";
                }
                else
                {
                    AdvanceFundRequest ar = new AdvanceFundRequest();
                    string PropNumber = txtPropNumber.Text;
                    int count = 25;
                    DataTable dtList = ar.GetProposalNumberList(DataAccess.GetConnectionString(), loggedID, txtPropNumber.Text.Trim(), count);
                    if (dtList.Rows.Count > 0)
                    {
                        dtList = GetInfoByProposalNumber(PropNumber);
                        if (dtList.Rows.Count > 0)
                        {
                            LoadPageData(dtList);
                        }
                        else
                        {
                            ClearPageData();
                            annunciator.Message = "This is not a valid Proposal Number.";
                        }
                    }
                    else
                    {
                        ClearPageData();
                        annunciator.Message = "This is not a valid Proposal Number.";
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        protected void imgBtnSaveDraft_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int StatusType = (int)WorkflowStatus.Draft;
                // Upload the documents if any and save the information to the table
                UploadDocumentsToSharePoint(lblPropNo.Text.Trim(), loggedInUserID, StatusType);
                // Save the request Info in the tables.
                SaveFundRequest(lblPropNo.Text.Trim(), loggedInUserID, txtComments.Text.Trim(), StatusType);

                // update the attachments list.
                DataTable dt = GetUploadedDocument(lblPropNo.Text.Trim());
                gvDocs.DataSource = dt;
                gvDocs.DataBind();

                // adding the client script for each view button.
                if (dt.Rows.Count > 0)
                {
                    foreach (GridViewRow row in gvDocs.Rows)
                    {
                        ImageButton lnkAction = (ImageButton)row.Cells[3].FindControl("ibView");
                        lnkAction.OnClientClick = "javascript:window.open('../Research/downloadform.aspx?FileUrl=" + lnkAction.ToolTip.ToString() + "', 'OpenFile', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    }
                }

                // update the number the upload controls.
                for (int i = 5; i > 5 - dt.Rows.Count; i--)
                {
                    FileUpload fup = new FileUpload();
                    fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                    fup.Visible = false;
                }
                if (fu1.Visible == false)
                {
                    fu1.Visible = true;
                    fu1.Enabled = false;
                }
                annunciator.Message = "Fund Request saved successfully.";
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }            
        }

        protected void imgBtnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int Status = (int)WorkflowStatus.AwaitingPISignoff;
                int EmailedToId = 0;
                string EmailSubject = "";
                string EmailId = "";
                DataTable dt = null;
                string Requestor = "";
                UserContext user = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);

                dt = GetInfoByProposalNumber(lblPropNo.Text.Trim());
                if (Convert.ToInt32(dt.Rows[0]["PIId"].ToString()) == loggedInUserID)
                {
                    Status = (int)WorkflowStatus.AwaitingDepartmentSignoff;
                    EmailedToId = Convert.ToInt32(dt.Rows[0]["ChiefId"].ToString() == "" ? "0" : dt.Rows[0]["ChiefId"].ToString());
                    EmailId = dt.Rows[0]["ChiefEmailId"].ToString() + ";" + dt.Rows[0]["DelegateEmailId"].ToString();
                    Requestor = dt.Rows[0]["PIName"].ToString();
                }
                else if (Convert.ToInt32(dt.Rows[0]["ChiefId"].ToString() == "" ? "0" : dt.Rows[0]["ChiefId"].ToString()) == loggedInUserID || Convert.ToInt32(dt.Rows[0]["DelegateId"].ToString() == "" ? "0" : dt.Rows[0]["DelegateId"].ToString()) == loggedInUserID)
                {
                    Status = (int)WorkflowStatus.AwaitingGASignoff;
                    EmailedToId = Convert.ToInt32(dt.Rows[0]["GAId"].ToString() == "" ? "0" : dt.Rows[0]["GAId"].ToString());
                    EmailId = dt.Rows[0]["GAEmailId"].ToString();
                    Requestor = dt.Rows[0]["ChiefName"].ToString();
                }
                else
                {
                    EmailedToId = Convert.ToInt32(dt.Rows[0]["PIId"].ToString());
                    EmailId = dt.Rows[0]["PIEmailId"].ToString() + ";" + dt.Rows[0]["DAEmailId"].ToString();                        
                    Requestor = user.LastName + ", " + user.FirstName;
                }                    
                // Upload the documents if any and save the information to the table
                UploadDocumentsToSharePoint(lblPropNo.Text.Trim(), loggedInUserID, Status);
                // Save all the request information. 
                SaveFundRequest(lblPropNo.Text.Trim(), loggedInUserID, txtComments.Text.Trim(), Status);
                
                // Send email notification
                if (Status == (int)WorkflowStatus.AwaitingPISignoff)
                {
                    EmailSubject = "ACTION: Advance Fund Request Has Been Submitted";
                }
                else
                {
                    EmailSubject = "ACTION: Advance Fund Request requires your Approval";
                }
                CreateEmailMessage(Requestor, dt.Rows[0]["Title"].ToString(), dt.Rows[0]["PIName"].ToString(), dt.Rows[0]["SponsorName"].ToString(), dt.Rows[0]["PeriodDate"].ToString(), EmailSubject, EmailId);  

                // Log notification data to table.
                SaveFundRequestEmailNotification(lblPropNo.Text.Trim(), EmailedToId, loggedInUserID, EmailSubject, EmailTemplate, Status);
                imgBtnSaveDraft.Visible = false;
                imgBtnSubmit.Visible = false;

                // update the attachments list.
                dt = GetUploadedDocument(lblPropNo.Text.Trim());
                gvDocs.DataSource = dt;
                gvDocs.DataBind();

                // adding the client script for each view button.
                if (dt.Rows.Count > 0)
                {
                    foreach (GridViewRow row in gvDocs.Rows)
                    {
                        ImageButton lnkAction = (ImageButton)row.Cells[3].FindControl("ibView");
                        lnkAction.OnClientClick = "javascript:window.open('../Research/downloadform.aspx?FileUrl=" + lnkAction.ToolTip.ToString() + "', 'OpenFile', 'resizable=yes, status=yes, scrollbars=yes');return false;";
                    }
                }

                // update the number the upload controls.
                for (int i = 2; i <= 5; i++)
                {
                    FileUpload fup = new FileUpload();
                    fup = (FileUpload)tblMin.FindControl("fu" + i.ToString());
                    fup.Visible = false;
                }
                fu1.Enabled = false;
                imgBtnInfo.Enabled = false;
                txtPropNumber.Enabled = false;
                gvDocs.Columns[(int)AttachmentsTableColumnIndex.Delete].Visible = false;
                annunciator.Message = "Fund Request submitted successfully.";              
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }
                
        protected void gvDocs_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                string FileUrl = "";
                if (e.CommandName.ToLower() == "deletedoc")
                {
                    FileUrl = e.CommandArgument.ToString().Trim();
                    DeleteFundRequestDocument(FileUrl);
                }                
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }  
        }
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect(Settings.GetKeyValue("SubNavigation.Agreements.AgreementSummaryURL", ""),false);
        }

        /// <summary>
        /// Method to create the HTML Email Message and send it.
        /// </summary>
        /// <param name="Requestor"></param>
        /// <param name="Title"></param>
        /// <param name="PIName"></param>
        /// <param name="Sponsor"></param>
        /// <param name="ProjDate"></param>
        /// <param name="EmailSubject"></param>
        /// <param name="EmailId"></param>
        private void CreateEmailMessage(string Requestor, string Title, string PIName, string Sponsor, string ProjDate, string EmailSubject, string EmailId)
        {
            EmailTemplate = "<html>" + Utility.Settings.GetKeyValue("Email.AdvanceFundRequest.Body", "ACTION NEEDED: An advance fund request has been submitted for your approval. Pls. review the following information and use the link included to take action.");
            EmailTemplate = EmailTemplate + "<br><br><ul>";
            EmailTemplate = EmailTemplate + "<li>" + "Requestor : " + Requestor + "</li>";
            EmailTemplate = EmailTemplate + "<li>" + "Requested Date : " + DateTime.Today.ToShortDateString() + "</li>";
            EmailTemplate = EmailTemplate + "<li>" + "Project Title : " + Title + "</li>";
            EmailTemplate = EmailTemplate + "<li>" + "PI : " + PIName + "</li>";
            EmailTemplate = EmailTemplate + "<li>" + "Sponsor : " + Sponsor + "</li>";
            EmailTemplate = EmailTemplate + "<li>" + "Project S/E Date : " + ProjDate + "</li>";
            EmailTemplate = EmailTemplate + "</ul><br>";
            EmailTemplate = EmailTemplate + "Link to form within Insight to approve" + "<br>" + PageUrl + "?id=" + lblPropNo.Text.Trim() + "</html>";

            string[] EId = EmailId.Split(';');
            for (int i = 0; i < EId.Length; i++)
            {
                SendEmailNotification(EId[i].ToString(), EmailSubject, EmailTemplate);
            }
        }
    }
}